<template>
  <div>

    <!------------------     聊天页面     ---------------->
    <div style="padding: 10px; margin-bottom: 50px">
      <el-row>
        <el-col :span="16">
          <div style="width: 800px; margin: 0 auto; background-color: white;
                    border-radius: 5px; box-shadow: 0 0 10px #ccc">
            <div style="text-align: center; line-height: 50px;">
              <span style="font-size: 30px">{{ patient.recordName }}&nbsp;</span>{{patient.recordSex}}&nbsp;{{patient.recordAge}}
            </div>
            <div style="height: 350px; overflow:auto; border-top: 1px solid #ccc" v-html="content"></div>
            <div style="height: 200px">
            <textarea v-model="text" style="height: 160px; width: 100%; padding: 20px; border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; outline: none"></textarea>
              <div style="text-align: right; padding-right: 10px">
                <el-button type="primary" size="mini" @click="send">发送</el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { findThisCharHistory, findThisRecordByPatientId } from '@/api/doctor/receivePatients.js'
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      form: {},
      patient: {},
      prescriptionForm: {
        prescription: {
          diagnosticResult: undefined,
          patientId: undefined,
          diagnosticDiseaseDescription: undefined
        },
        prescriptionDrugMiddleList: []
      },
      messages: [],
      myId: undefined,
      text1: undefined,
      content: []
    }
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    // 这里是 setup 函数中使用的其他逻辑，需要根据需要在 data 或 methods 中进行定义
    return {}
  },
  created() {
    this.init();
    this.myId = userStore.state.id; // 获取当前用户的 ID
    this.getRecordByPatientId(); // 获取病人的记录
    this.findCharHistory()
  },
  methods: {
    getRecordByPatientId() {
      this.prescriptionForm.value.prescription.patientId = this.$route.query.patientId;
      this.findThisRecordByPatientId(this.$route.query.patientId).then(res => {
        this.patient.value = res.data;
      });
    },
    send() {
      if (!this.prescriptionForm.value.prescription.patientId) {
        this.$message({ type: 'warning', message: '请选择聊天对象' });
        return;
      }
      if (!this.text1) {
        this.$message({ type: 'warning', message: '请输入内容' });
      } else {
        if (typeof WebSocket === 'undefined') {
          console.log('您的浏览器不支持WebSocket');
        } else {
          let message = { from: this.myId.value, to: this.prescriptionForm.value.prescription.patientId, text: this.text1 };
          this.socket.send(JSON.stringify(message));
          this.messages.push({ user: this.myId.value, text: this.text1 });
          this.createContent(null, this.myId.value, this.text1);
          this.text1 = '';
        }
      }
    },
    createContent(remoteUser, nowUser, text1) {
      let html;
      if (nowUser) {
        html = `<div class="el-row" style="padding: 5px 0">
          <div class="el-col el-col-22" style="text-align: right; padding-right: 10px">
            <div class="tip left">${text1}</div>
          </div>
          <div class="el-col el-col-2">
            <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
              <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
            </span>
          </div>
        </div>`;
      } else if (remoteUser) {
        html = `<div class="el-row" style="padding: 5px 0">
          <div class="el-col el-col-2" style="text-align: right">
            <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
              <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
            </span>
          </div>
          <div class="el-col el-col-22" style="text-align: left; padding-left: 10px">
            <div class="tip right">${text1}</div>
          </div>
        </div>`;
      }
      this.content += html;
    },
    init() {
      let username = this.myId.value;
      if (typeof WebSocket === 'undefined') {
        console.log('您的浏览器不支持WebSocket');
      } else {
        let socketUrl = `ws://localhost:9301/imserver/${username}`;
        if (this.socket !== null) {
          this.socket.close();
          this.socket = null;
        }
        this.socket = new WebSocket(socketUrl);
        this.socket.onopen = () => {
          console.log('websocket已打开');
        };
        this.socket.onmessage = (msg) => {
          let data = JSON.parse(msg.data);
          if (data.from === this.prescriptionForm.value.prescription.patientId) {
            this.messages.push(data);
            this.createContent(data.from, null, data.text1);
          }
        };
        this.socket.onclose = () => {
          console.log('websocket已关闭');
        };
        this.socket.onerror = () => {
          console.log('websocket发生了错误');
        };
      }
    },
    findCharHistory() {
      // 使用 Vue 提供的 this.$route 获取路由参数
      findThisCharHistory(this.$route.query.patientId).then(res => {
        console.log(res.data);
        res.data.forEach(chatHistory => {
          // 如果 from 等于 myId.value，证明是“我”发送的
          if (chatHistory.from === this.myId.value) {
            this.createContent(null, chatHistory.from, chatHistory.text1);
          } else {
            // 对方发送的
            this.createContent(chatHistory.from, null, chatHistory.text1);
          }
        });
      });
    },
  }
};
</script>

<style>

.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width: auto;
  display: inline-block;
}

.right {
  background-color: deepskyblue;
}

.left {
  background-color: forestgreen;
}

.prescription {
  margin: 50px auto;
  width: 800px;
  position: relative;
  text-align: center;
}

</style>